var fs = require('fs');
var path = require('path');


var fileDir = "";

function loadTemplate(pathname){
  fileDir = path.resolve(path.dirname(pathname));
  var fileContent = "";
  try {
    fileContent = fs.readFileSync(pathname, 'utf-8');
  } catch (e) {
    console.log("打开文件：" + pathname + "错误");
  }
  var newContent = loadDeep(fileContent);
  if(newContent != fileContent){
    fs.writeFileSync(pathname, newContent);
    console.log('模板应用到了：' + pathname);
  }
}

function loadDeep(fileContent){
  //  var a = document.getElementsByTagName("html")[0].replace(/#include\s?\(\\?[\'\"][^\'\"]+\\?[\'\"]\);?/g,
  //     var childFileSrc = str.replace(/[\\\'\"\>\(\);\s]/g, '').replace('#include', '');
  return fileContent.replace(/<!--\s?#include\sfile=\\?[\'\"][^\'\"]+\\?[\'\"]\s?-->/g, function(str){
  		var childFileSrc = str.replace(/[\\\'\"\>\(\);\s<!=-]/g, '').replace('#includefile', '');

      childFileSrc = path.join(fileDir,childFileSrc);
      var childFileContent = "";
      try {
        childFileContent = fs.readFileSync(childFileSrc, 'utf-8');
      } catch (e) {
        console.log("不能打开文件：" + childFileSrc + "！\n"+e);
        process.exit();
      }
      console.log("载入模板文件" + childFileSrc);
      return childFileContent;
  });
}

module.exports = loadTemplate;
